package tech.yangzhijie.basic.demo02.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {

    private static final String ENCODING = "utf-8";

    public static String sendPost(String url, Map<String, String> headers, JSONObject data, String encoding){
        //请求返回结果
        String resultJson = null;
        //
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost();
            httpPost.setURI(new URI(url));
            if(headers != null){
                Header[] allHeader = new BasicHeader[headers.size()];
                int i = 0;

                for (Map.Entry<String, String> entry: headers.entrySet()){
                    allHeader[i] = new BasicHeader(entry.getKey(), entry.getValue());
                    i++;
                }

                //httpPost.setHeaders(allHeader);
                httpPost.setHeader("content-type", "application/json");
                httpPost.setHeader("partner_code", "f1CcCdpcHrfCqjnF95dlsYqfxo0QCXno");
                System.out.println(JSON.toJSONString(data));
                httpPost.setEntity(new StringEntity(JSON.toJSONString(data),"UTF-8"));

                CloseableHttpResponse response = client.execute(httpPost);
                int status = response.getStatusLine().getStatusCode();
                if(status == HttpStatus.SC_OK){
                    resultJson = EntityUtils.toString(response.getEntity(),encoding);
                }else{
                    System.out.println("响应错误：错误码："+status);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultJson;
    }

    public static String sendPost(String url,Map<String,Object> params){
        // 设置默认请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        //headers.put("partner_code", "f1CcCdpcHrfCqjnF95dlsYqfxo0QCXno");
        headers.put("partner_code", "11");
        // 将map转成json
        JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
        System.out.println(data);
        return sendPost(url,headers,data,ENCODING);
    }

    public static String sendGet(String url) throws URISyntaxException, IOException {
        //请求返回结果
        String resultJson = null;
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet();
            httpGet.setURI(new URI(url));
            CloseableHttpResponse response = client.execute(httpGet);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                resultJson = EntityUtils.toString(response.getEntity(),"utf-8");
            }else{
                System.out.println("响应错误：错误码："+status);
            }
        }
        return resultJson;
    }


    @Test
    public void method(){
        String appId = "651051655379207001";
        String appSecretKey = "WYXEKWVIDNNT3YJOQVQI0KNGON5KEXSS";
        JSONObject data = new JSONObject();
        data.put("idCard","211381198901280830");
        data.put("name","李涵诺");
        data.put("youMengMobile","13516017457");
        data.put("mobile","13516017457");
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(new URI("https://themis.yingyinglicai.com/api/personal-data/youmeng/score"));
            String body = data.toJSONString();
            String message1 = "POST" + "\n" + body + "\n" + appId + "\n" + appSecretKey;
            String s = hmacSHA256(message1, appSecretKey);
            httpPost.setHeader("content-type", "application/json");
            httpPost.setHeader("Authorization", "HmacSHA256 appId="+appId+", signature="+s);
            httpPost.setEntity(new StringEntity(JSON.toJSONString(data),"UTF-8"));

            CloseableHttpResponse response = client.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_CREATED){
                System.out.println(data.toJSONString()+" 成功！");
            }else{
                System.out.println("响应错误：错误码："+status);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static String hmacSHA256(String message, String appSecretKey) {
        String signature = null;
        try {
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(appSecretKey.getBytes(), "HmacSHA256"));

            byte[] hash = hasher.doFinal(message.getBytes());

            // 获得十六进制形式的签名
            signature = DatatypeConverter.printHexBinary(hash).toLowerCase();
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }

        return signature;
    }

    public static void main(String[] args) {
        String appId = "302815394149826560";
        String appSecretKey = "6407BE85BB4E4DABBF18C34DC71B9DFB";

        String body = "{\"youMengMobile\":\"13516017457\",\"idCard\":\"211381198901280830\",\"name\":\"李涵诺\",\"mobile\":\"13516017457\"}";
        String message1 = "POST" + "\n" + body + "\n" + appId + "\n" + appSecretKey;

        String message2 = "GET" + "\n" + appId + "\n" + appSecretKey;

        System.out.println("POST ---> "+hmacSHA256(message1, appSecretKey));
        System.out.println("GET ---> "+hmacSHA256(message2, appSecretKey));
    }
}
